package com.hsnn.medstgmini.base.dict.controller;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.model.DicExperttype;
import com.hsnn.medstgmini.base.dict.service.DicExperttypeManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.ExcelUtil;
import com.hsnn.medstgmini.util.Pagination;


/**
 * @category 专家 类型
 * @author wangbing
 * @date 2015年7月13日
 */
@Controller
@RequestMapping("/dicExperttype")
public class DicExperttypeController {

	private static final Logger log = Logger.getLogger(DicExperttypeController.class);
			

	@Autowired
	private DicExperttypeManager dicExperttypeManager;

	@Autowired
	private HttpServletRequest request;
	
	
	/**
	 * @category 跳转专家类型页面
	 * @date 2015年7月13日
	 * @return String
	 */
	@RequestMapping("/toExperttypeList")
	public String toExperttypeList() {
		log.info("enter toExperttypeList method");
		return "/base/dict/experttypeList";
	}
	
	/**
	 * @category 获取专家类型列表
	 * @date 2015年7月13日
	 * @return page
	 */
	@RequestMapping("/getDicExperttypeList")
	@ResponseBody
	public Pagination getDicExperttypeList(){
		printParams();
		Pagination page = new Pagination(request);
		try {
			page.getConditions().put("expertTypeName", request.getParameter("expertTypeName"));
			page.getConditions().put("status", request.getParameter("status"));
			dicExperttypeManager.getDicExperttypeList(page);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return page;
	}
	
	
	/**
	 * 
	 *@category 批量启用停用
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping(value={"/enable","/disable"})
	@ResponseBody
	public Pagination batchChangeStatus(String array) {
		printParams();
		Pagination page = new Pagination();
		int count = 0;
		try {
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<DicExperttype>>() {
				}.getType();
				List<DicExperttype> list = gson.fromJson(array, type);
				if (list != null && list.size()>0) {
					for (DicExperttype dds : list) {
						dds.setUpdUser(user.getId());
						count = dicExperttypeManager.changeStatus(dds);
					}
					page.setSuccess(true);
					page.getConditions().put("count", count+"");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	
	
	
	
	/**
	 * 新增或编辑
	 * @param page
	 */
	@RequestMapping("/dicSysAddOrUpdate")
	@ResponseBody
	public Pagination dicSysAddOrUpdate(){
		printParams();
		Pagination page = new Pagination();
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		page.getConditions().put("updUser", user.getId());
		if(StringUtils.isNotBlank(request.getParameter("expertTypeCode"))){
			page.getConditions().put("expertTypeCode", request.getParameter("expertTypeCode").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("expertTypeName"))){
			page.getConditions().put("expertTypeName", request.getParameter("expertTypeName").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("dicExperttypeId"))){
			page.getConditions().put("dicExperttypeId", request.getParameter("dicExperttypeId").trim());
		}
		if(StringUtils.isNotBlank(request.getParameter("fatherExperttypeId"))){
			page.getConditions().put("fatherExperttypeId", request.getParameter("fatherExperttypeId").trim());
		}else{
			page.getConditions().put("fatherExperttypeId", "0");
		}
		try {
			if(request.getParameter("dicExperttypeId")!=null){
				if(StringUtils.isNotBlank(request.getParameter("dicExperttypeId"))){
					//update
					if(StringUtils.isNotBlank(request.getParameter("dicExperttypeId"))){
						List<DicExperttype> list=dicExperttypeManager.getDicExperttypeBy("expertTypeName",request.getParameter("expert_type_name").trim(),request.getParameter("dicExperttypeId"));
		            	 if(list.size()>0){
		            		 page.setMsg("类型名称已存在!");
		            		 page.setSuccess(false);
		            		 return page;
		                 }
		            }else{
		            	page.setMsg("请输入类型名称!");
		            	page.setSuccess(false);
		            	return page;
		            }
					dicExperttypeManager.updateDicExperttype(page);
					page.setMsg("修改成功!");
					page.setSuccess(true);
				}else{
					//add
					if(StringUtils.isNotBlank(request.getParameter("dicExperttypeId"))){
						List<DicExperttype> list=dicExperttypeManager.getDicExperttypeBy("expertTypeName",request.getParameter("expert_type_name").trim(),request.getParameter("dicExperttypeId"));
		            	 if(list.size()>0){
		            		 page.setMsg("类型名称已存在!");
		            		 page.setSuccess(false);
		            		 return page;
		                 }
		            }else{
		            	page.setMsg("请输入类型名称!");
		            	page.setSuccess(false);
		            	return page;
		            }
					
		            String expertTypeAddId = UUID.randomUUID().toString();
		            page.getConditions().put("expertTypeAddId", expertTypeAddId);
		            if(!"0".equals(request.getParameter("fatherExperttypeId"))){
		            	dicExperttypeManager.addDicExperttype(page);
						page.setMsg("保存成功!");
						page.setSuccess(true);
		            }else{
		            	if(StringUtils.isNotBlank(request.getParameter("expertTypeCode1"))){
		            		page.getConditions().put("expertTypeName", request.getParameter("expertTypeName1").trim());
		            		dicExperttypeManager.addDicExperttype(page);
		            		page.getConditions().put("expertTypeName", request.getParameter("expertTypeName").trim());
		            		page.getConditions().put("expertTypeAddId", UUID.randomUUID().toString());
		            		page.getConditions().put("fatherExperttypeId", expertTypeAddId);
		            		dicExperttypeManager.addDicExperttype(page);
							page.setMsg("保存成功!");
							page.setSuccess(true);
		            	}else{
		            		dicExperttypeManager.addDicExperttype(page);
							page.setMsg("保存成功!");
							page.setSuccess(true);
		            	}
		            }
					
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			page.setMsg("保存失败!");
			page.setSuccess(false);
		}
		return page;
		
	}
	
	/**
	 * 保存新增的数据
	 * @param page
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Pagination addSave(){
		printParams();
		Pagination page = new Pagination();
		try {
			String array = request.getParameter("array");
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			if (StringUtils.isBlank(array)) {
				page.setSuccess(false);
				return page;
			}
			Gson gson = new Gson();
			Type type = new TypeToken<List<Map<String,String>>>() {
			}.getType();
			List<Map<String,String>> list = gson.fromJson(array, type);
			if(list.size()==1){
				List<DicExperttype> expList=dicExperttypeManager.getDicExperttypeBy("expert_type_name",list.get(0).get("expertTypeName"),"");
			 	if(expList.size()>0){
			 		page.setMsg("专家类型名称已存在!");
			 		page.setSuccess(false);
			 		return page;
			    }
			 	page.getConditions().put("dicExperttypeId", UUID.randomUUID().toString());
			 	page.getConditions().put("expertTypeName", list.get(0).get("expertTypeName"));
			 	page.getConditions().put("fatherId", list.get(0).get("fatherId"));
			 	page.getConditions().put("updUser", user.getId());
			    dicExperttypeManager.addDicExperttype(page);
				page.setSuccess(true);
			 	
			}else if(list.size()==2){
				List<DicExperttype> expList=dicExperttypeManager.getDicExperttypeBy("expert_type_name",list.get(1).get("expertTypeName"),"");
			 	if(expList.size()>0){
			 		page.setMsg("二级类型名称已存在!");
			 		page.setSuccess(false);
			 		return page;
			    }
			 	String uuid = UUID.randomUUID().toString();
			 	page.getConditions().put("dicExperttypeId",uuid);
			 	page.getConditions().put("expertTypeName", list.get(0).get("expertTypeName"));
			 	page.getConditions().put("fatherId", list.get(0).get("fatherId"));
			 	page.getConditions().put("updUser", user.getId());
			    dicExperttypeManager.addDicExperttype(page);
			    
			    page.getConditions().put("dicExperttypeId",UUID.randomUUID().toString());
			 	page.getConditions().put("expertTypeName", list.get(1).get("expertTypeName"));
			 	page.getConditions().put("fatherId", uuid);
			 	page.getConditions().put("updUser", user.getId());
			    dicExperttypeManager.addDicExperttype(page);
				page.setSuccess(true);
			}else if(list.size()==3){
				List<DicExperttype> expList=dicExperttypeManager.getDicExperttypeBy("expert_type_name",list.get(2).get("expertTypeName"),"");
			 	if(expList.size()>0){
			 		page.setMsg("三级类型名称已存在!");
			 		page.setSuccess(false);
			 		return page;
			    }
			 	String uuid1 = UUID.randomUUID().toString();
			 	page.getConditions().put("dicExperttypeId",uuid1);
			 	page.getConditions().put("expertTypeName", list.get(0).get("expertTypeName"));
			 	page.getConditions().put("fatherId", list.get(0).get("fatherId"));
			 	page.getConditions().put("updUser", user.getId());
			    dicExperttypeManager.addDicExperttype(page);
			    
			    String uuid2 = UUID.randomUUID().toString();
			    page.getConditions().put("dicExperttypeId",uuid2);
			 	page.getConditions().put("expertTypeName", list.get(1).get("expertTypeName"));
			 	page.getConditions().put("fatherId", uuid1);
			 	page.getConditions().put("updUser", user.getId());
			    dicExperttypeManager.addDicExperttype(page);
			    
			    page.getConditions().put("dicExperttypeId",UUID.randomUUID().toString());
			 	page.getConditions().put("expertTypeName", list.get(2).get("expertTypeName"));
			 	page.getConditions().put("fatherId", uuid2);
			 	page.getConditions().put("updUser", user.getId());
			    dicExperttypeManager.addDicExperttype(page);
				page.setSuccess(true);
			}else {
				page.setSuccess(false);
			}
		} catch (Exception e) {
			page.setMsg("数据异常");
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
	/**
	 * 
	 *@category 检查是否重复
	 *@author wangbing
	 *@date 2015年7月27日
	 *Pagination
	 */
	@RequestMapping("/checkRepeat")
	@ResponseBody
	public Pagination checkRepeat() {
		printParams();
		Pagination page = new Pagination();
		String expertTypeName = request.getParameter("expertTypeName");
		
		try {
	            if(StringUtils.isNotBlank(expertTypeName)){
	            	List<DicExperttype> list=dicExperttypeManager.getDicExperttypeBy("expert_type_name",expertTypeName.trim(),"");
	            	 if(list.size()>0){
	            		 page.setMsg("专家类型名称已存在!");
	            		 page.setSuccess(false);
	            		 return page;
	                 }else{
	                	 page.setSuccess(true);
	                 }
	            }else{
	            	page.setMsg("请输入专家类型名称!");
	            	page.setSuccess(false);
	            	return page;
	            }
			
		} catch (Exception e) {
			e.printStackTrace();
			page.setMsg(e.toString());
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 * 
	 *@category 保存编辑的数据
	 *@author wangbing
	 *@date 2015年7月27日
	 *Pagination
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Pagination editSave(){
		printParams();
		Pagination page = new Pagination(request);
		try {
			String typeName = request.getParameter("typeName");
			String dicExperttypeId = request.getParameter("dicExperttypeId");
			if(StringUtils.isBlank(typeName)){
				page.setSuccess(false);
				page.setMsg("专家类型名称不能为空!");
				return page;
			}
			List<DicExperttype> list=dicExperttypeManager.getDicExperttypeBy("expert_type_name",typeName.trim(),dicExperttypeId);
			if(list.size()>0){
				page.setMsg("专家类型名称已存在!");
				page.setSuccess(false);
				return page;
			}
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			page.getConditions().put("updUser", user.getId());
			page.getConditions().put("expertTypeName", typeName.trim());
			page.getConditions().put("dicExperttypeId", dicExperttypeId);
			dicExperttypeManager.updateDicExperttype(page);
			page.setMsg("操作成功!");
			page.setSuccess(true);
		} catch (Exception e) {
			page.setMsg("数据异常!");
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
	
	/**
	 * 
	 *@category 获取参数打印
	 *@author 徐国鹏
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("rawtypes")
	public void printParams(){
		Enumeration paramNames = request.getParameterNames();
		try {
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				log.info(paramName+":"+paramValue);
			}
		} catch (Exception e) {
			log.error("",e);
		}
	}
	
	/**
	 * 
	 *@category 导出excel
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping("exportExcel")
	@ResponseBody
	public Pagination exportExcel(HttpServletResponse response,String fileName){
		printParams();
		Pagination page = new Pagination();
		String expertTypeName = request.getParameter("expertTypeName");
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(expertTypeName)){
			page.getConditions().put("expertTypeName", expertTypeName.trim());
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status.trim());
		}
		try {
			response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("GB2312"),"iso8859-1")); 
			OutputStream os= new BufferedOutputStream(response.getOutputStream());  
			 response.setContentType("application/vnd.ms-excel;charset=utf-8");  
			 dicExperttypeManager.getDicExperttypeNoPage(page);
			 String title = "专家类型";
			 String[] headers = {"一级类型名称","二级类型名称","三级类型名称","状态"};
			 String[] alias = {"firstLevelName","secoLevelName","thirdLevelName","status"};
			 ExcelUtil.exportExcel(page, os, title, headers, alias);
		} catch (Exception e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
}
